//
//  NYTopicArticlesViewController.m
//  Nooryes
//
//  Created by baken on 2020/3/4.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYTopicArticlesViewController.h"
#import "NYTopicViewModel.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "NYRecommendCollectionViewCell.h"
#import "NYArticleListModel.h"
#import "NYTopicDetailModel.h"
#import "NYArticleDetailViewController.h"
#import "NYRecommendViewModel.h"
#import "NYAlertView.h"
#import "AccountModel.h"
#import "NYLoginViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface NYTopicArticlesViewController ()<UICollectionViewDataSource,CHTCollectionViewDelegateWaterfallLayout>
@property (weak, nonatomic) IBOutlet UIImageView *backImg;
@property (weak, nonatomic) IBOutlet UIImageView *topicImg;
@property (weak, nonatomic) IBOutlet UILabel *mytitle;
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *read;
@property (weak, nonatomic) IBOutlet UILabel *collect;
@property (weak, nonatomic) IBOutlet UIImageView *avatar;
@property (weak, nonatomic) IBOutlet UIView *redLine;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;

@property (nonatomic, strong) UIButton *selectedBtn;

@property(nonatomic, strong) NYTopicViewModel *topicVM;

@property (nonatomic, strong) NYRecommendViewModel *recommendVM;



@end

@implementation NYTopicArticlesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[NYRecommendCollectionViewCell class] forCellWithReuseIdentifier:kNYRecommendCollectionViewCell];
    
    self.topicVM.topicID = self.topicID;
    [self.topicVM getTopicDetailWithCompletionHandle:^(NSError *error) {
        if (!error) {
            [self.backImg sd_setImageWithURL:[NSURL URLWithString:self.topicVM.deatil.headimg]];
            [self.avatar sd_setImageWithURL:[NSURL URLWithString:self.topicVM.deatil.userimg]];
            [self.topicImg sd_setImageWithURL:[NSURL URLWithString:self.topicVM.deatil.headimg]];
            self.mytitle.text = self.topicVM.deatil.name;
            self.name.text = self.topicVM.deatil.nickname;
            self.content.text = self.topicVM.deatil.intro;
            self.date.text = self.topicVM.deatil.dateline;
            self.read.text = self.topicVM.deatil.count;
            self.collect.text = self.topicVM.deatil.collect;
            if (self.topicVM.deatil.iscollect) {
                [self.collectBtn setImage:[UIImage imageNamed:@"btn_collection_r"] forState:UIControlStateNormal];
            }
            
            
        }
    }];
    self.topicVM.order = @"0";
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.topicVM refreshArticlesCompletionHandle:^(NSError *error) {
            [self.collectionView reloadData];
            [self.collectionView.mj_header endRefreshing];
        }];
        
    }];
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self.topicVM getMoreArticlesCompletionHandle:^(NSError *error) {
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        }];
    }];
    [self.collectionView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLogin) name:@"login" object:nil];
}

-(void)didLogin{
    [self.recommendVM getArticleDetailWithCompletionHandle:^(NSError *error) {
        if (!error) {
            
            if (self.topicVM.deatil.iscollect) {
                [self.collectBtn setImage:[UIImage imageNamed:@"btn_collection_r"] forState:UIControlStateNormal];
            }
            
        }
    }];
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UICollectionView Delegate


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.topicVM.articlesArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NYRecommendCollectionViewCell *cell = [NYRecommendCollectionViewCell cellWithCollectionView:collectionView indePath:indexPath];
    ArticleListModel *model = [self.topicVM.articlesArray objectAtIndex:indexPath.row];
    cell.model = model;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            if (!CGSizeEqualToSize(model.imageSize, image.size)) {
                model.imageSize = image.size;
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
    }];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ArticleListModel *model = [self.topicVM.articlesArray objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
    NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
    detailVC.articleID = model.articleid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    ArticleListModel *model = [self.topicVM.articlesArray objectAtIndex:indexPath.row];
    if (!CGSizeEqualToSize(model.imageSize, CGSizeZero)) {
        return model.imageSize;
    }
    return CGSizeMake(150, 150);
}


- (IBAction)onCollect:(id)sender {
    if ([self isLogin]) {
        [self.topicVM collectArticleWithCompletionHandle:^(NSError *error) {
            NYAlertView *alert = [NYAlertView sharedAlertView];
            if (!error) {
                if (self.topicVM.deatil.iscollect) {
                    myDelegate.account.collect++;
                    alert.title = @"收藏成功";
                    [self.collectBtn setImage:[UIImage imageNamed:@"btn_collection_r"] forState:UIControlStateNormal];
                } else {
                    myDelegate.account.collect--;
                    alert.title = @"取消收藏成功";
                    [self.collectBtn setImage:[UIImage imageNamed:@"btn_collect"] forState:UIControlStateNormal];
                }
                
            } else {
                alert.title = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            }
            [alert showAlert:^{ }];
        }];
    }
}

- (IBAction)onShare:(id)sender {
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:self.topicVM.deatil.intro
                                     images:@[self.topicVM.deatil.headimg]
                                        url:[NSURL URLWithString:self.topicVM.deatil.shareurl]
                                      title:self.topicVM.deatil.name
                                       type:SSDKContentTypeAuto];
    
    [ShareSDK showShareActionSheet:nil
                       customItems:nil
                       shareParams:shareParams
                sheetConfiguration:nil
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
            if (platformType != SSDKPlatformTypeWechat) {
                NYAlertView *alert = [NYAlertView sharedAlertView];
                alert.title = @"分享成功";
                [alert showAlert:^{ }];
                break;
            }
            }
            case SSDKResponseStateFail:
            {
            NYAlertView *alert = [NYAlertView sharedAlertView];
            alert.title = @"分享失败";
            [alert showAlert:^{ }];
            break;
            }
            default:
                break;
        }
    }];
}

- (IBAction)onNew:(id)sender {
    self.selectedBtn.selected = NO;
    UIButton *btn = (UIButton *)sender;
    btn.selected = YES;
    self.selectedBtn = btn;
    self.redLine.center = CGPointMake(btn.center.x, self.redLine.center.y);
    
    self.topicVM.order = @"0";
    [self.collectionView.mj_header beginRefreshing];
}

- (IBAction)onHot:(id)sender {
    self.selectedBtn.selected = NO;
    UIButton *btn = (UIButton *)sender;
    btn.selected = YES;
    self.selectedBtn = btn;
    self.redLine.center = CGPointMake(btn.center.x, self.redLine.center.y);
    
    self.topicVM.order = @"1";
    [self.collectionView.mj_header beginRefreshing];
}


-(NYTopicViewModel *)topicVM{
    if (!_topicVM) {
        _topicVM = [NYTopicViewModel new];
    }
    return _topicVM;
}
- (IBAction)onUser:(id)sender {
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    UIViewController *destination = segue.destinationViewController;
    if ([destination respondsToSelector:@selector(setUserID:)]) {
        
        [destination setValue:self.topicVM.deatil.userid forKey:@"userID"];
    }
}

-(NYRecommendViewModel *)recommendVM{
    if (!_recommendVM) {
        _recommendVM = [NYRecommendViewModel new];
    }
    return _recommendVM;
}

- (BOOL)isLogin{
    if (myDelegate.account) {
        return YES;
    } else {
        //        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请先登录后评论。" message:nil preferredStyle:UIAlertControllerStyleAlert];
        //        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        //        [alertVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"NYLoginStoryboard" bundle:nil];
        NYLoginViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"NYLoginViewController"];
        vc.controller = self;
        [self.navigationController pushViewController:vc animated:YES];
        //        }]];
        //        [self presentViewController:alertVC animated:YES completion:nil];
        return NO;
    }
}



@end
